/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dale2507.gates.gate;

import dale2507.gates.events.GateStatusChangeEvent;
import dale2507.gates.exceptions.GateException;
import dale2507.gates.exceptions.VerificationException;
import org.bukkit.Bukkit;
import org.bukkit.Material;

/**
 *
 * @author Dale
 */
public final class Gate {
    
    public static enum Status {BROKEN, DISABLED, INACTIVE, DIALLING, OUTGOING, RECEIVING, INCOMING};
    
    private IRing ring;
    private DHD dhd;
    private Display display;
    
    private GateSettings settings;
    
    private Status status = Status.INACTIVE;
    private Activator activator;

    public Gate(GateSettings settings, IRing ring, DHD dhd, Display display) throws VerificationException {
        this.settings = settings;
        this.ring = ring;
        this.dhd = dhd;
        this.display = display;
        
        Material torchType = this.settings.getTorchType();
        this.ring.setChevronMaterial(torchType);
        
        this.dhd.setGate(this);
        this.display.setGate(this);
        this.ring.setGate(this);
        this.ring.init();
    }

    public GateSettings getSettings() {
        return settings;
    }

    public DHD getDhd() {
        return dhd;
    }

    public Display getDisplay() {
        return display;
    }

    public IRing getRing() {
        return ring;
    }
    
    public Status getStatus() {
        return status;
    }
    
    void setStatus(Status status) {
        GateStatusChangeEvent event = new GateStatusChangeEvent(this, this.getStatus(), status);
        Bukkit.getServer().getPluginManager().callEvent(event);
        
        this.status = status;
    }

    public void setEnabled(boolean enabled) throws GateException {
        if (this.status == Gate.Status.DISABLED && enabled) {
            this.setStatus(Gate.Status.INACTIVE);
        } else if (!enabled) {
            if (this.status == Gate.Status.RECEIVING || this.status == Gate.Status.INCOMING)
                throw new GateException("Cannot disable a gate while it is recieving a connection");
            
            this.getActivator().deactivate(null);
            this.setStatus(Gate.Status.DISABLED);
            this.display.refreshStatus();
            this.ring.getIris().setEngaged(true);
        }
    }
    
    public Activator getActivator() {
        if (this.activator == null) this.activator = new Activator(this);
        return this.activator;
    }
    
    public void removeListeners() {
        this.ring.removeListeners();
        this.dhd.removeListeners();
        this.display.removeListeners();
    }
    
}
